package com.qf.openapi.web.master.interceptor;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j

public class AutoLoginInterceptor implements HandlerInterceptor {

    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 免登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //
        User user = (User) request.getSession().getAttribute(Constants.SISSION_USER_KEY);
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(Constants.USER_TOKEN)) {
                        String value = cookie.getValue();
                        String[] split = value.split("-");
                        final String username = split[0];
                        final String password = split[1];
                        User loginUser = userService.login(username, password);
                        request.getSession().setAttribute(Constants.SISSION_USER_KEY,loginUser);
                        response.sendRedirect("/ssm2202/plateform.html");
                        return false;
                    }
                }
            }

        } else {
            response.sendRedirect("/ssm2202/plateform.html");
            return false;
        }
        return true;
    }

}
